//
//  NHttpManager.m
//  Nan
//
//  Created by NOMIS-WORKSPACE on 12/5/14.
//  Copyright (c) 2014 ZhanAo. All rights reserved.
//

#import "BmHttpManager.h"
#import "AFNetworking.h"
#import "BmLoginViewController.h"

@implementation BmHttpManager

DEFINE_SINGLETON(BmHttpManager)

- (void)POST:(NSString*)url withParameters:(NSDictionary*)parameters  success:( void (^) (id data))success
{
    [self POST:url withParameters:parameters success:success failure:^(NSError *error) {
        
    }];
}

- (void)POST:(NSString*)url withParameters:(NSDictionary*)parameters  success:( void (^) (id data))success failure : ( void (^) (NSError *error))failure
{
    url = [NSString stringWithFormat:@"%@%@" , DOMAIN_URL , url];
    DDLogDebug(@"REQUEST URL IS : %@" , url);
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    [dic setObject:[BmUtil bm_getDeviceIdentity] forKey:@"deviceToken"];

    if ([[BmUserSession sharedInstance] sessionValid]){
        [dic setObject:[BmUserSession sharedInstance].token forKey:@"token"];
        [dic setObject:[BmUserSession sharedInstance].user.userId forKey:@"identify"];
    }

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:url parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        DDLogError(@"%@" , responseObject);
       if ([[responseObject objectForKey:@"success"] integerValue] == 1) {
           [KVNProgress dismiss];
            success(responseObject);
        }else{
            
            failure(NSError.new);
            NSInteger errorCode = [[responseObject objectForKey:@"errorCode"] integerValue];
            if (errorCode == 2003 || errorCode == 2004 || errorCode == 2005){
                [KVNProgress dismiss];
                /*
                 "2003":"token验证失败",
                 "2004":"登陆设备改变",
                 "2005":"token已过期",
                 需要登录的时候，进入到登录界面
                 */
                [[UIApplication sharedApplication].delegate window].rootViewController = [[BmNavigationController alloc] initWithRootViewController:BmLoginViewController.new];

            }else{
                [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"message"]];
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if(![self isNetworkingReachability])
            [KVNProgress showErrorWithStatus:@"当前网络不可用"];
        else
            [KVNProgress showErrorWithStatus:@"请求出错啦！"];
        failure(error);
    }];
}

- (BOOL)isNetworkingReachability
{
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    return afNetworkReachabilityManager.isReachable;
}

@end
